package com.github.yoojia.flow.impl;

import com.github.yoojia.flow.Context;
import com.github.yoojia.flow.Event;
import com.github.yoojia.flow.EventDelivery;
import com.github.yoojia.flow.VirtualDevice;
import com.parkingwang.lang.data.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 本地设备事件派发处理器
 * @author 陈哈哈 yoojiachen@gmail.com
 */
public class LocalDeviceEventDelivery implements EventDelivery {

    private static final Logger LOGGER = LoggerFactory.getLogger(LocalDeviceEventDelivery.class);

    @Override
    public void onInit(Context context, Config configs) throws Exception {
        // nop
    }

    @Override
    public void onStart() {
        // nop
    }

    @Override
    public void onStop() {
        // nop
    }

    @Override
    public Event onDeliverEvent(Context context, Event event) {
        // 锁定序列ID，以防修改。
        final long sequence = event.sequence;

        // 由本地事件目标设备来执行动作：
        // 1. 目标地址不是远程地址
        // 2. 目标地址不是空的
        if (/*NOT*/!Context.ADDRESS_NONE.equals(event.destAddress) &&
                /*NOT*/!event.isRemoteDestAddress()) {
            final VirtualDevice device = context.findLocalDevice(event.destAddress);
            if (device != null) {
                try {
                    return device.handleEvent(context, event);
                } catch (Throwable e) {
                    LOGGER.error("Error when VirtualDevice processing", e);
                    return Event.simple(sequence, Context.TOPIC_SYS_ERROR);
                }
            } else {
                LOGGER.warn("Event send to local, Target device NOT FOUND, event: {}", event);
                return Event.simple(sequence, Context.TOPIC_SYS_NOT_FOUND);
            }
        } else {
            // 不是本地事件，跳过
            return Event.simple(sequence, Context.TOPIC_SYS_SKIPPED);
        }
    }

}
